/**
 * 饼图专题图
 */
/**
 * 饼图
 * 说明：能适应单指标、多指标的展示（考虑多指标时可以转变为多条折线图）
 * data = [{
       id: 'pie',
       name: '饼图',
       regioncode: "aaa",
       regionname: "aaa",
       lon: "70.92866163503169",
       lat: "78.830660058696104",
       showThumbnails:false,
       width: '100px',
       heigth: '100px',
       data: [{
           value: 335,
           name: '直接访问'
         },
         {
           value: 310,
           name: '邮件营销'
         },
         {
           value: 234,
           name: '联盟广告'
         },
         {
           value: 135,
           name: '视频广告'
         },
         {
           value: 1548,
           name: '搜索引擎'
         }
        ]
     }]
 *
 */
import store from "../../../../pages/macro/store";
import { getMapLayers } from "vuex";
import echarts from 'echarts'; // echarts 文件引入
import styleModify from './echarts.stylemodify'; // 设置图层的可见性，透明度，zIndex文件引入
import colorPicker from './echarts.colorpicker'; // 颜色初始化配置文件
import sgisLayerBase from '../../sfgis.layer.base';
import $ from 'jquery'
export default {
  activeMap: {}, // 当前活动地图
  pieLayer: '',
  callback:"",
  pieLayerInfo: {}, // 图层其他相关信息
  /**
   * 创建地图饼图专题图
   */
  createLayer(map, data, callback) {
    var compare = function(obj1, obj2) {
      var val1 = Number(obj1.regioncode);
      var val2 = Number(obj2.regioncode);
      if (val1 < val2) {
        return -1;
      } else if (val1 < val2) {
        return 1;
      } else {
        return 0;
      }
    };
    data.data = data.data.sort(compare);
    $(".pie_chart").remove();
    if (!map) {
      return;
    }
    if (!data || !data.data.length) {
      return;
    }
    this.callback = callback
    this.activeMap = map;
    let pieMarkers = this.createMarker(data.data, map); // 创建好所有marker
    // let pieLayer = L.layerGroup(pieMarkers)
    //   .addTo(map);
    let pieLayer = pieMarkers;
    styleModify.onZoom(this.activeMap, pieMarkers); // 为markers绘图添加缩放监听改变z-Index;

    // this.pieLayer = pieLayer;
    // 此处必须先把容器加到地图上才能加载图表
    this.clickPieIcon();

    this.pieLayer = pieLayer;
    // 将容器加载到地图容器
    this.createCharts(pieMarkers, data.data);
    // 自定义颜色开始
    let id = "pie_chart_" + data.id + "_" + +new Date();
    // 设置容器初始ZINdex,为后面调整图层顺序功能 开始
    styleModify.setLayerOrder(styleModify.curZindex, pieLayer, id);
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    styleModify.layerOrder[id] = styleModify.curZindex;
    styleModify.curZindex -= 1;
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    pieLayer.setCustomColor = this.setCustomColor;
    pieLayer.setOpacity = styleModify.setOpaticty; // 设置图层透明度
    pieLayer.setVisible = styleModify.setVisible; // 设置图层可见性
    pieLayer.setZIndexOffset = this.setZIndexOffset; // 设置调整图层顺序函数;
    pieLayer.layerId = id;
    pieLayer.calgraph = this.calgraph;
    // 自顶替颜色结束
    this.pieLayerInfo = {
      name: data.name,
      type: "pie",
      layerId: "pie",
      show: data.showThumbnails !== false,
      // layer: pieLayer,
    };
    store.commit("getMapLayers", this.pieLayerInfo)

    map.overlayers["pie"] = pieLayer
    map.overlayerInfos["pie"] = this.pieLayerInfo

    return this.pieLayerInfo;
  },
  /**
   * 创建echarts容器
   */
  createMarker(datas, map) {
    let resultMarkers = [];
    for (let i = 0; i < datas.length; i++) {
      let time = +new Date();
      // 初始化最小宽高开始
      let width = colorPicker.size;
      let data = datas[i];
      if (data.hasOwnProperty('width')) {
        width = data.width.slice(0, -2);
        width = parseInt(width);
        if (width < colorPicker.size) {
          width = colorPicker.size;
        }
      }
      let height = colorPicker.size;
      if (data.hasOwnProperty('height')) {
        height = data.width.slice(0, -2);
        height = parseInt(height);
        if (height < colorPicker.size) {
          height = colorPicker.size;
        }
      }
      let iconWidth = width + 45;
      let iconHeight = height + 45;
      // 初始化最小宽高结束

      var el = document.createElement('div');
      el.className = `pie_chart chart_background`;
      el.id = "pie_chart_" + i + time;
      el.style.width = 120 + 'px';
      el.style.height = 120 + 'px';
      let chartMarker = new mapboxgl.Marker(el)
        .setLngLat([data.lon, data.lat])
        .addTo(map);

      resultMarkers.push(chartMarker);
    }

    return resultMarkers;
  },
  /**
   * 创建图表
   * @param {Object} pieMarkers 图表容器
   * @param {Object} datas 数据
   */
  createCharts(pieMarkers, datas) {
    if (datas.length <= 5) {
      let i = 1;
      let optionTimer = setInterval(() => {
        let dataValue = datas.slice(0, i)
        this.getNewOptionList(dataValue,pieMarkers)
        i++;
        if (i > datas.length) {
          this.pieLayerInfo["html"] = this.calgraph("pie");
          
          sgisLayerBase.setOverLayers(this.pieLayerInfo);
          this.pieLayer.charts = [...this.charts];
          this.callback(this.pieLayerInfo)
          clearInterval(optionTimer)
        }
      }, 500)

    }else{
      let i = 5;
      let optionTimer = setInterval(() => {
        let dataValue = datas.slice(0, i)
        this.getNewOptionList(dataValue,pieMarkers)
        i+=5;
        if (i-datas.length > 5) {
          this.pieLayerInfo["html"] = this.calgraph("pie");
          
          sgisLayerBase.setOverLayers(this.pieLayerInfo);
          this.pieLayer.charts = [...this.charts];
          this.callback(this.pieLayerInfo)
          clearInterval(optionTimer)
        }
      }, 500)
    }
  },
  getNewOptionList(datas,pieMarkers) {
    let charts = [];
    for (let i = 0; i < datas.length; i++) {
      this.graph = [];
      let chart = echarts.init(document.getElementById(pieMarkers[i]._element.id));
      let chartOption = {
        color: store.state.macro.layerColors["pie"] ? store.state.macro.layerColors["pie"] : colorPicker.color,
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        series: [{
          name: datas[i].name,
          type: 'pie',
          radius: '50%',
          center: ['50%', '60%'],
          data: datas[i].data,
          labelLine: {
            show: false
          },
          label: {
            show: false
          },
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      chart.setOption(chartOption);
      charts.push({
        id: pieMarkers[i]._element.id,
        echart: chart
      });
      /* *计算图例参数 */
      let colors;
      if (store.state.macro.layerColors["pie"]) {
        colors = store.state.macro.layerColors["pie"];
      } else {
        colors = colorPicker.color;
      }
      for (let key in datas[i].data) {
        let index = key % colors.length;
        let color = colors[index];
        this.graph.push({
          name: datas[i].data[key].name,
          color
        });
      }
    }

    this.charts = charts;
  },
  /**
   * @param {object} {
     pieStyle: ["red", "green", "skyblue", "yellow", "tomato"]
   }
   par
   */
  setCustomColor(layers, pars) {
    let par = {};
    par = {
      ...pars,
      pieStyle: pars.colors
    };
    for (let key in layers.charts) {
      let item = layers.charts[key];
      let option = item.echart.getOption();
      // 设置饼图颜色开始
      if (par.hasOwnProperty('pieStyle')) {
        option.color = par.pieStyle;
      }
      store.commit("layerColors", { type: "pie", color: par.pieStyle })
      // 设置饼图颜色结束
      item.echart.clear();
      item.echart.setOption(option);
      // 设置图例颜色 开始
      let colors = item.echart.getOption().color;
      let datas = option.series;
      this.graph = [];
      for (let key in datas[0].data) {
        let index = key % colors.length;
        let color = colors[index];
        this.graph.push({
          name: datas[0].data[key].name,
          color
        });
      }
      // 设置图例颜色 结束
    }
    layers.calgraph("pie", pars.colors);
  }, // 自定义饼图颜色函数
  calLend(datas) {
    let ledend = [];
    for (let item of datas) {
      ledend.push(item.name);
    }
    return ledend;
  },
  /**
   * @param {string} layerId 图层id
   */

  clickPieIcon() {
    let els = document.querySelectorAll('i[pie]');
    for (let i = 0; i < els.length; i++) {
      let el = els[i];
      el.onclick = () => {
        let id = el.getAttribute('pie');
        for (let key in this.charts) {
          if (this.charts[key].id === id) {
            let options = this.charts[key].echart.getOption();
            options.series[0].radius = ['50%', '70%'];
            this.charts[key].echart.setOption(options);
            return;
          }
        }
      };
    }
    // 变换成环形图
    let els_r = document.querySelectorAll('i[reset]');
    for (let i = 0; i < els_r.length; i++) {
      let el = els_r[i];
      el.onclick = () => {
        let id = el.getAttribute('reset');
        for (let key in this.charts) {
          if (this.charts[key].id === id) {
            let options = this.charts[key].echart.getOption();
            options.series[0].radius = '55%';
            this.charts[key].echart.setOption(options);
            return;
          }
        }
      };
    }
    // 变换成饼图
  },
  /* *设置图例样式 开始 */
  calgraph(layerId) {
    let html = `<div style="padding:6px" class="${layerId}">`;
    for (let key in this.graph) {
      html += `<div class='chart_item' style='display:flex;align-items: center;justify-content: flex-start;position: relative;'>
        <div style = 'position: absolute;left:-8px;display:inline-block;width:0px;height:0px;margin:0;padding:0;border-radius:50px;border:10px solid transparent;border-right-color:${this.graph[key].color};'> 
        </div>
        <p style="margin-left:20px">${this.graph[key].name}</p>
      </div>`;
    }
    html += '</div>';
    let layers = sgisLayerBase.overLayers;
    layers.map(item => {
      if (item.type == layerId) {
        item.html = html
      }
    })
    return html;
  },
  autoCalgraph(layerId) {
    let html = `<div style="padding:10px" class="${layerId}">`;
    for (let key in this.graph) {
      html += `<div class='chart_item' style='display:flex;align-items: center;justify-content: flex-start;position: relative;'>
        <div style = 'position: absolute;left:-8px;display:inline-block;width:0px;height:0px;margin:0;padding:0;border-radius:50px;border:10px solid transparent;border-right-color:${this.graph[key].color};'>
        </div>
        <p style="margin-left:20px">${this.graph[key].name}</p>
      </div>`;
    }
    html += '</div>';


  },
  /* *设置图例样式 结束 */
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this._layers);
  }
};
